import React, { useEffect, useState } from "react"
import { Tag, Tooltip } from "antd"

interface ITagViewerProps {
  maxWidth?:number
  tags:Array<{name:string,value:string}>
}
function TagViewer(props:ITagViewerProps) {
  const containerRef = React.useRef(null);
  const [visibleTags, setVisibleTags] = React.useState(props.tags);
  const [disVisibleTags, setDisVisibleTags] = React.useState([])
  const tags = props.tags
  const maxWidth = props.maxWidth || 1000
  useEffect(()=>{
    if (containerRef.current) {
      containerRef.current.style.cssText = ''
    }
  })
  useEffect(() => {
    if (containerRef.current) {
      containerRef.current.style.cssText = 'width:calc(100% - 400px)'
      const containerWidth = containerRef.current.offsetWidth;
      //console.log('容器的宽度:', containerWidth, 'cssText',containerRef.current.style.cssText);

      let totalWidth = 0;
      const visibleTags = [];
      const disVisibleTags = []

      for (let i = 0; i < tags.length; i++) {
        const tagWidth = getTagWidth(tags[i]);
        if (totalWidth + tagWidth <= containerWidth) {
          visibleTags.push(tags[i]);
          totalWidth += tagWidth;
        } else {
          //break;
          disVisibleTags.push(tags[i])
        }
      }

      setVisibleTags(visibleTags);
      setDisVisibleTags(disVisibleTags)
    }
  }, [tags]);

  const getTagWidth = (tag) => {
    const tempTag = document.createElement('span');
    tempTag.style.visibility = 'hidden';
    tempTag.style.whiteSpace = 'nowrap';
    tempTag.style.padding = '0 8px'; // 根据实际的 padding 调整
    tempTag.style.fontSize = '14px'; // 根据实际的 fontSize 调整
    tempTag.style.borderRadius = '2px'; // 根据实际的 borderRadius 调整
    tempTag.style.border = '1px solid #d9d9d9'; // 根据实际的 border 调整
    tempTag.style.backgroundColor = '#fafafa'; // 根据实际的 backgroundColor 调整
    tempTag.style.display = 'inline-block';
    tempTag.textContent = tag.name;
    document.body.appendChild(tempTag);
    const width = tempTag.getBoundingClientRect().width;
    document.body.removeChild(tempTag);
    return width;
  };

  return (
    <div className="tag-viewer" ref={containerRef} style={{ maxWidth, overflow: 'hidden' }}>
      {visibleTags.map((item, index) => {
        const colors = ['green', 'blue', 'cyan', 'red', 'orange', 'purple'];
        return <Tag color={colors[index]} key={item.name}>{item.name}</Tag>;
      })}
      {tags.length > visibleTags.length && <Tooltip title={disVisibleTags.map(item=>item.name).join(',')}><Tag>+{tags.length - visibleTags.length}</Tag></Tooltip>}
    </div>
  );
}

export default TagViewer
